import os;
cfgFileDict = {}
ROOT=os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
class TemplateFile:
    def __init__(self,inFile):
        self.InFile=inFile
    def read_in(self):
        from utils import file2lines
        self.lines = file2lines(self.InFile)
    def replace(self,prop,val):
        index = 0
        for line in self.lines:
            if(-1!=line.find(prop)):
                self.lines [index] = line.replace(prop,val)
            index = index + 1
    def merge(self,templateFile):
        self.lines = self.lines + templateFile.lines
    def write_out(self,outFile):
        f = open(outFile,'w', encoding="gbk")
        f.writelines(self.lines)
        f.close()
        
class MeshGen:
    def __init__(self,type='spr'):
        self.cfgDict={}
        self.type=type
    def set_config(self,proValues={}):
        self.proValues = proValues
    def load_template(self,temp_file=None):
        #print(temp_file)
        if temp_file is None:
            temp_file = os.path.join(ROOT,cfgFileDict[self.type])
        else:
            temp_file = os.path.join(os.getcwd(),temp_file)
        #print(111,temp_file)
        self.tf = TemplateFile(temp_file)
        self.tf.read_in()
    def set_cfg(self):
        self.proKeys=self.proValues.keys()
        for aKey in self.proKeys:
            proValue=self.proValues[aKey]
            self.tf.replace(aKey,str(proValue))
    def write_cfg(self,cfgFiles):
        self.tf.write_out(cfgFiles)
        self.cfgFiles = cfgFiles
    # def run_meshgen(self):
    #     console_cmd ('mesh27.exe %s'%self.cfgFiles,show_on_console=False,wait=True)
    def clear(self,filelist = []):
        import os;
        import shutil
        os.makedirs('_tmp',exist_ok=True)
        shutil.move('myconfig.inp','_tmp/myconfig.inp')
        shutil.move('my_console_out.log','_tmp/my_console_out.log')
        try:
            for i in range(1,1000):
                shutil.move('test_%d.facet'%i,'_tmp/test_%d.facet'%i)
        except:
            pass
        try:
            for file in filelist:
                shutil.move(file,'_tmp/%s'%file)
        except:
            pass
class GeodesicConfig(MeshGen):
    def set_geodesic_root(self,geodesic_root):
        self.geodesic_root = geodesic_root
    def run_meshgen(self):
        from utils import console_cmd
        strCMD = f'{self.geodesic_root}//Geodesic20.exe {self.cfgFiles}'
        #print(strCMD)
        console_cmd(strCMD,show_on_console=True,wait=True)
    def results(self):
        from utils import file2lines
        results_file = self.proValues["<file_name>"]+".txt"
        lines = file2lines(f'{self.geodesic_root}//temp//{results_file}')
        return float(lines[0])